package com.mapforge.map.tilewriter;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Iterator;
import java.util.List;

import com.mapforge.map.Tile;
import com.mapforge.map.TileLayer;
import com.mapforge.map.Tileset;
import com.mapforge.selection.ComparablePoint;
import com.mapforge.selection.Selection;
import com.mapforge.selection.TileSelection;

public class SequentialTileWriter extends AbstractTileWriter {

	@Override
	public void previewWrite(Graphics2D g, TileSelection tileSelection,
			Selection destination) {
	}

	@Override
	public List<Tile> writeTiles(TileSelection tileSelection, Selection destination) {
		Rectangle srcRect = tileSelection.getBoundingRectangle();
		Rectangle dstRect = destination.getBoundingRectangle();
		Point origin = new Point(dstRect.x, dstRect.y);

		int right = origin.x + srcRect.width;
		int bottom = origin.y + srcRect.height;
		Iterator<ComparablePoint> it = destination.iterator();
		TileLayer layer = getTileLayer();
		Tileset tileset = getTileset();
		ComparablePoint p;

		while (it.hasNext()) {
			p = it.next();
			if (p.x < right && p.y < bottom
					&& tileSelection.contains(p.x - origin.x, p.y - origin.y)) {
				layer.setTile(p.x, p.y, tileset.getTileAt(p.x - origin.x, p.y
						- origin.y));
			}
		}
		return null;
	}
}